<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\user;

use app\adminapi\controller\Base;
use app\adminapi\validate\user\VipValidate;
use app\common\model\UserVip;
use app\common\model\UserVipRecord;
use app\common\model\User;
use think\facade\Db;

class Vip extends Base
{
    /**
     * Get VIP level list
     */
    public function lists()
    {
        $vipModel = new UserVip();
        $res      = $vipModel::paginate($this->limit);

        return $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }

    /**
     * Get VIP level details
     */
    public function detail()
    {
        $id = $this->request->get('id', 0);
        if (!$id) {
            return $this->error(trans('parameter_error'));
        }

        $vip = UserVip::find($id);
        if (!$vip) {
            return $this->error(trans('vip_level_not_exists'));
        }

        return $this->success('', $vip);
    }

    /**
     * Add VIP level
     */
    public function add()
    {
        $validate = new VipValidate();
        $data     = $validate->data('add');

        $vipModel = new UserVip();
        $vipModel->save($data);

        return $this->success();
    }

    /**
     * Edit VIP level
     */
    public function edit()
    {
        $validate = new VipValidate();
        $data     = $validate->data('edit');

        $vip = UserVip::find($data['id']);
        if (!$vip) {
            return $this->error(trans('vip_level_not_exists'));
        }

        $vip->save($data);

        return $this->success();
    }

    /**
     * Delete VIP level
     */
    public function del()
    {
        $id = $this->request->post('id', 0);
        if (!$id) {
            return $this->error(trans('parameter_error'));
        }

        // Check if there are users using this VIP level
        $recordCount = UserVipRecord::where('vip_id', $id)
            ->where('status', 1)
            ->count();

        if ($recordCount > 0) {
            return $this->error(trans('vip_level_has_users'));
        }

        $vip = UserVip::find($id);
        if (!$vip) {
            return $this->error(trans('vip_level_not_exists'));
        }

        $vip->delete();

        return $this->success();
    }

    /**
     * Modify VIP level status
     */
    public function status()
    {
        $validate = new VipValidate();
        $data     = $validate->data('status');

        $vip = UserVip::find($data['id']);
        if (!$vip) {
            return $this->error(trans('vip_level_not_exists'));
        }

        $vip->status = $vip->status == 1 ? 0 : 1;
        $vip->save();

        return $this->success();
    }

    /**
     * Initialize default VIP levels
     */
    public function initDefault()
    {
        // Insert data into the database, do not translate the original language
        $defaultVips = [
            [
                'name'              => 'VIP月卡',
                'icon'              => '/static/images/vip/vip1.png',
                'price'             => 30.00,
                'duration'          => 30,
                'exclusive_content' => 0,
                'description'       => 'VIP月卡会员权益',
                'status'            => 1,
                'points_reward'     => 30
            ],
            [
                'name'              => 'VIP季卡',
                'icon'              => '/static/images/vip/vip2.png',
                'price'             => 88.00,
                'duration'          => 90,
                'exclusive_content' => 1,
                'description'       => 'VIP季卡会员权益',
                'status'            => 1,
                'points_reward'     => 100
            ],
            [
                'name'              => 'VIP年卡',
                'icon'              => '/static/images/vip/vip3.png',
                'price'             => 298.00,
                'duration'          => 365,
                'exclusive_content' => 1,
                'description'       => 'VIP年卡会员权益',
                'status'            => 1,
                'points_reward'     => 400
            ]
        ];

        $vipModel = new UserVip();
        foreach ($defaultVips as $vip) {
            $exists = $vipModel->where('name', $vip['name'])->find();
            if (!$exists) {
                $vipModel->create($vip);
            }
        }

        return $this->success();
    }

    /**
     * Get user VIP record list
     */
    public function records()
    {
        // Get GET and POST parameters
        $user_id      = $this->request->get('user_id', $this->request->post('user_id', 0));
        $status       = $this->request->get('status', $this->request->post('status', ''));
        $order_status = $this->request->get('order_status', $this->request->post('order_status', ''));
        $sort         = $this->request->get('sort', $this->request->post('sort', 'create_time'));
        $order        = $this->request->get('order', $this->request->post('order', 'desc'));
        $page         = $this->request->get('page', $this->request->post('page', 1));
        $limit        = $this->request->get('limit', $this->request->post('limit', $this->limit));

        $where = [];
        if ($user_id) {
            $where[] = ['user_id', '=', $user_id];
        }
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        if ($order_status !== '') {
            $where[] = ['order_status', '=', $order_status];
        }

        // Validate sort fields
        $allowedSortFields = ['create_time', 'start_time', 'end_time', 'id'];
        if (!in_array($sort, $allowedSortFields)) {
            $sort = 'create_time';
        }

        // Validate sort direction
        $order = strtolower($order) === 'asc' ? 'asc' : 'desc';

        $recordModel = new UserVipRecord();
        $res         = $recordModel->where($where)
            ->with(['user', 'vip'])
            ->order($sort . ' ' . $order)
            ->paginate($limit, false)->each(function ($item) {
                $item->user_name = $item->user->username ?? '';
                $item->vip_name = $item->vip->name ?? '';
                return $item;
            });

        return $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }

    /**
     * Set user VIP
     */
    public function setUserVip()
    {
        $post     = $this->request->post();
        $validate = new VipValidate();
        $data     = $validate->data('setUserVip', $post);

        // Check if user exists
        $user = User::find($data['user_id']);
        if (!$user) {
            return $this->error(trans('member_not_exists'));
        }

        // Check if VIP level exists
        $vip = UserVip::find($data['vip_id']);
        if (!$vip) {
            return $this->error(trans('vip_level_not_exists'));
        }

        // Get duration
        $duration = $data['duration'] ?? $vip->duration;

        // Start transaction
        Db::startTrans();
        try {
            // Set user VIP
            $startTime = time();
            $endTime   = $startTime + $duration * 86400;

            // Create VIP record
            $record             = new UserVipRecord();
            $record->user_id    = $data['user_id'];
            $record->vip_id     = $data['vip_id'];
            $record->start_time = date('Y-m-d H:i:s', $startTime);
            $record->end_time   = date('Y-m-d H:i:s', $endTime);
            $record->status     = 1;
            $record->save();

            // Update user VIP expiration time
            $user->vip_expire_time = date('Y-m-d H:i:s', $endTime);
            $user->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
        return $this->success();
    }

    /**
     * Edit VIP start time, end time and activation status
     */
    public function editVipTime()
    {
        $record_id  = $this->request->post('record_id', 0);
        $start_time = $this->request->post('start_time', '');
        $end_time   = $this->request->post('end_time', '');
        $status     = $this->request->post('status', 0);

        $record = UserVipRecord::find($record_id);
        if (!$record) {
            return $this->error(trans('vip_record_not_exists'));
        }

        $record->start_time = $start_time;
        $record->end_time   = $end_time;
        $record->status     = $status;
        $record->save();

        // Update to user
        $user = User::find($record->user_id);
        if (!$user) {
            return $this->error(trans('member_not_exists'));
        }
        $user->vip_expire_time = $end_time;
        $user->save();

        return $this->success();
    }

    /**
     * Cancel user VIP
     */
    public function cancelUserVip()
    {
        $validate = new VipValidate();
        $data     = $validate->data('cancelUserVip');

        // Check if VIP record exists
        $record = UserVipRecord::find($data['record_id']);
        if (!$record) {
            return $this->error(trans('vip_record_not_exists'));
        }

        // Check if user exists
        $user = User::find($record->user_id);
        if (!$user) {
            return $this->error(trans('member_not_exists'));
        }

        // Start transaction
        Db::startTrans();
        try {
            // Cancel VIP record
            $record->status = 0;
            $record->save();

            // Check if user has other active VIP records
            $activeRecord = UserVipRecord::where('user_id', $user->id)
                ->where('status', 1)
                ->where('end_time', '>', date('Y-m-d H:i:s'))
                ->order('end_time', 'desc')
                ->find();

            if ($activeRecord) {
                // Update user VIP expiration time to the latest active record
                $user->vip_expire_time = $activeRecord->end_time;
            } else {
                // Clear user VIP expiration time
                $user->vip_expire_time = null;
            }

            $user->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
        return $this->success();
    }

    /**
     * Delete VIP record
     */
    public function delVipRecord()
    {
        $record_id = $this->request->post('record_id', 0);
        if (!$record_id) {
            return $this->error(trans('parameter_error'));
        }

        $record = UserVipRecord::find($record_id);
        if (!$record) {
            return $this->error(trans('vip_record_not_exists'));
        }

        $record->delete();

        return $this->success();
    }

    /**
     * Get server current time
     */
    public function getCurrentTime()
    {
        return $this->success('', [
            'current_time' => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * Calculate end time
     */
    public function calculateEndTime()
    {
        $start_time = $this->request->post('start_time', '');
        $period     = $this->request->post('period', '');

        if (!$start_time || !$period) {
            return $this->error(trans('parameter_error'));
        }

        $startTimestamp = strtotime($start_time);
        if (!$startTimestamp) {
            return $this->error(trans('start_time_format_error'));
        }

        // Calculate end time based on period
        switch ($period) {
            case '1month':
                $endTimestamp = strtotime('+1 month', $startTimestamp);
                break;
            case '6months':
                $endTimestamp = strtotime('+6 months', $startTimestamp);
                break;
            case '1year':
                $endTimestamp = strtotime('+1 year', $startTimestamp);
                break;
            default:
                return $this->error(trans('unsupported_time_period'));
        }

        $endTime = date('Y-m-d H:i:s', $endTimestamp);

        return $this->success('', [
            'end_time' => $endTime
        ]);
    }

    /**
     * VIP充值记录在线补单
     */
    public function manualPayment()
    {
        $record_id = $this->request->post('record_id', 0);
        $remark    = $this->request->post('remark', '管理员手动补单');

        if (!$record_id) {
            return $this->error(trans('parameter_error'));
        }

        $record = UserVipRecord::find($record_id);
        if (!$record) {
            return $this->error(trans('vip_record_not_exists'));
        }

        if ($record->status == 1) {
            return $this->error(trans('vip_record_already_paid'));
        }

        // 开始事务
        Db::startTrans();
        try {
            // 更新VIP记录状态
            $record->status   = 1;
            $record->remark   = $remark;
            $record->pay_time = date('Y-m-d H:i:s');
            $record->save();

            // 更新用户VIP到期时间
            $user = User::find($record->user_id);
            if (!$user) {
                throw new \Exception(trans('member_not_exists'));
            }

            // 计算用户VIP到期时间
            $endTime = strtotime($record->end_time);
            if ($user->vip_expire_time && strtotime($user->vip_expire_time) > time()) {
                // 如果用户已有VIP且未过期，则延长时间
                $currentExpireTime = strtotime($user->vip_expire_time);
                $vip               = UserVip::find($record->vip_id);
                if ($vip) {
                    $newExpireTime         = $currentExpireTime + ($vip->duration * 86400);
                    $user->vip_expire_time = date('Y-m-d H:i:s', $newExpireTime);
                } else {
                    $user->vip_expire_time = $record->end_time;
                }
            } else {
                // 如果用户没有VIP或已过期，则直接设置为记录中的到期时间
                $user->vip_expire_time = $record->end_time;
            }

            $user->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * VIP充值记录在线退款
     */
    public function refund()
    {
        $record_id     = $this->request->post('record_id', 0);
        $refund_reason = $this->request->post('refund_reason', '管理员手动退款');

        if (!$record_id) {
            return $this->error(trans('parameter_error'));
        }

        $record = UserVipRecord::find($record_id);
        if (!$record) {
            return $this->error(trans('vip_record_not_exists'));
        }

        if ($record->order_status != 1) {
            return $this->error(trans('only_paid_vip_record_can_refund'));
        }

        // 开始事务
        Db::startTrans();
        try {
            // 更新VIP记录状态
            $record->order_status  = 3; // 3表示已退款
            $record->refund_time   = date('Y-m-d H:i:s');
            $record->refund_reason = $refund_reason;
            $record->save();

            // 检查用户是否有其他有效VIP记录
            $user = User::find($record->user_id);
            if (!$user) {
                throw new \Exception(trans('member_not_exists'));
            }

            $activeRecord = UserVipRecord::where('user_id', $user->id)
                ->where('status', 1)
                ->where('end_time', '>', date('Y-m-d H:i:s'))
                ->where('id', '<>', $record_id) // 排除当前被退款的记录
                ->order('end_time', 'desc')
                ->find();

            if ($activeRecord) {
                // 更新用户VIP到期时间为最新的有效记录
                $user->vip_expire_time = $activeRecord->end_time;
            } else {
                // 清空用户VIP到期时间
                $user->vip_expire_time = null;
            }

            $user->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }
}